package com.android.huimeiqupin.fragment.detail;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.huimeiqupin.activity.BaseObject;
import com.android.huimeiqupin.activity.GoodsDetailActivity;
import com.android.huimeiqupin.activity.GoodsStoreActivity;
import com.android.huimeiqupin.adapt.GridDetaillikeAdapt;
import com.android.huimeiqupin.fragment.BaseLazyFragment;
import com.android.huimeiqupin.model.group.MainList;
import com.android.huimeiqupin.model.group.MainListCallback;
import com.android.huimeiqupin.utils.ConstantsUrl;
import com.android.huimeiqupin.utils.HttpUtils;
import com.android.huimeiqupin.utils.ObjectUtils;
import com.android.huimeiqupin.view.MyGridView;
import com.android.huimeiqupin.view.dialog.MainMsg;
import com.android.huimeiqupin.view.group.CountDownTimerView;
import com.android.huimeiqupin.R;
import com.android.huimeiqupin.model.detail.MainDetail;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 商品详情页
 */
public class Fragment_Detail_Goods extends BaseLazyFragment {
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.detail_title)
    TextView detailTitle;
    @BindView(R.id.title_type)
    TextView titleType;
    @BindView(R.id.aa_tuan_tv)
    TextView aaTuanTv;
    @BindView(R.id.detail_title_after)
    TextView detailTitleAfter;
    @BindView(R.id.detail_title_before)
    TextView detailTitleBefore;
    @BindView(R.id.aa_tuan_tv2)
    TextView aaTuanTv2;
    @BindView(R.id.detail_tuan)
    TextView detailTuan;
    @BindView(R.id.detail_rule)
    WebView detailWebViewrule;
    @BindView(R.id.detail_list_laituantuijiang)
    NestFullListView detailListLaituantuijiang;
    @BindView(R.id.ll_pintuanvis)
    LinearLayout llPintuanvis;
    @BindView(R.id.detail_like_grid)
    MyGridView detailLikeGrid;

    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.top)
    ImageView top;
    @BindView(R.id.recommend_reason)
    TextView recommendReason;
    @BindView(R.id.indicator)
    TextView indicator;

    @BindView(R.id.detail_webView)
    WebView detailWebView;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    @BindView(R.id.rule_type)
    TextView ruleType;
    @BindView(R.id.rule)
    LinearLayout rule;
    @BindView(R.id.banner)
    RelativeLayout banner;
    @BindView(R.id.nodata)
    TextView nodata;
    @BindView(R.id.adder_price_before)
    TextView adderPriceBefore;
    @BindView(R.id.adder_tuan)
    TextView adderTuan;
    @BindView(R.id.adder_gridview)
    MyGridView adderGridview;
    @BindView(R.id.adder_ll)
    LinearLayout adderLl;
    @BindView(R.id.pin_ll)
    LinearLayout pin_ll;
    @BindView(R.id.comss_price)
    TextView comssPrice;
    @BindView(R.id.comss_ll)
    LinearLayout comssLl;
    @BindView(R.id.h_title)
    TextView store_hor_title;
    @BindView(R.id.grid)
    NestFullListView store_hor_list;
    @BindView(R.id.progress_hot_tv)
    TextView store_hor_progress_tv;
    @BindView(R.id.progress_hot)
    RelativeLayout store_hor_progress;
    @BindView(R.id.h_ll)
    LinearLayout hLl;
    @BindView(R.id.store_logo)
    ImageView storeLogo;
    @BindView(R.id.store_name)
    TextView storeName;
    @BindView(R.id.store_goods)
    TextView storeGoods;
    @BindView(R.id.store_sell)
    TextView storeSell;
    @BindView(R.id.store_msg)
    LinearLayout storeMsg;
    @BindView(R.id.adder_price)
    TextView adderPrice;
    @BindView(R.id.adder_team_num_yes)
    TextView adderTeamNumYes;
    @BindView(R.id.adder_team_price)
    TextView adderTeamPrice;
    @BindView(R.id.adder_team_progress)
    ProgressBar adderTeamProgress;
    @BindView(R.id.adder_team_ll)
    LinearLayout adderTeamLl;
    @BindView(R.id.recommend_num)
    TextView recommendNum;
    private FragmentActivity mcontext;
    private View view;
    private LayoutInflater inflater;
    private int type;
    private GridDetaillikeAdapt adapter_like;
    private int detailid;
    private BannerAdapt adapter_banner;
    private boolean networkConnected;
    private String storeid;

    public Fragment_Detail_Goods() {
    }

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM3 = "param3";
    private MainDetail response;
    private int iskaipin;
    private ArrayList<MainList.MainListdata.Mainlistdata> listdata = new ArrayList<>();
    private ArrayList<String> Banner = new ArrayList<>();

    public static Fragment_Detail_Goods newInstance(MainDetail param1, int iskaipin) {
        Fragment_Detail_Goods fragment = new Fragment_Detail_Goods();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, param1);
        args.putInt(ARG_PARAM3, iskaipin);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            response = (MainDetail) getArguments().getSerializable(ARG_PARAM1);
            iskaipin = getArguments().getInt(ARG_PARAM3);
        }
    }

    @Override
    protected void initPrepare() {
    }

    private void initLayout() {
        detailTitleBefore.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        adderPriceBefore.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        adapter_like = new GridDetaillikeAdapt(mcontext, listdata);
        detailLikeGrid.setAdapter(adapter_like);
        WebSettings settings = detailWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        detailWebView.setWebChromeClient(new MyWebChromeClient());
        detailWebView.setWebViewClient(new MyWebViewClient());
        WebSettings settings2 = detailWebViewrule.getSettings();
        settings2.setJavaScriptEnabled(true);
        detailWebViewrule.setWebChromeClient(new MyWebChromeClient());
        detailWebViewrule.setWebViewClient(new MyWebViewClient());
        detailLikeGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ObjectUtils.ToDetailActivity(mcontext, 1, listdata.get(position).getId(), "");
            }
        });
        initBanner();
    }



    private void initBanner() {
        adapter_banner = new BannerAdapt();
        pager.setAdapter(adapter_banner);
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                CharSequence text = getString(R.string.viewpager_indicator,
                        position + 1, pager.getAdapter().getCount());
                indicator.setText(text);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        GetDetailData();
        GetDataListData("&typeid=1");
    }

    class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
        }
    }

    class MyWebViewClient extends WebViewClient {
        //拦截网址
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        detailWebView.getSettings().setJavaScriptEnabled(false);
        detailWebViewrule.getSettings().setJavaScriptEnabled(false);
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_detail_goods, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        initLayout();
        return view;
    }

    private void GetDetailData() {
        MainDetail.DataBean data = response.getData();
        if (data != null) {
            initWebContent();
            type = data.getTypeid();
            detailid = data.getId();
            String team_price = data.getTeam_price();
            String price = data.getPrice();
            SpannableString msp = new SpannableString("￥" + team_price);
            msp.setSpan(new AbsoluteSizeSpan(13, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            detailTitleBefore.setText("￥" + price);
            adderPriceBefore.setText("￥" + price);
            detailTuan.setText("已有" + data.getTeam_people_num() + "人参团");
            adderTuan.setText("已有" + data.getTeam_people_num() + "人参团");
            String desc = data.getDesc();
            if (desc == null || desc.equals("")) {
                recommendReason.setText("暂无推荐理由");
            } else {
                recommendReason.setText("" + desc);
            }
            int num_no = (Integer.parseInt(data.getTeam_num())) - 1;
            recommendNum.setText(num_no + "");
            detailTitleAfter.setText(msp);
            aaTuanTv.setText("");
            aaTuanTv2.setVisibility(View.GONE);

            List<MainDetail.DataBean.TeamListBean> team_list = data.getTeam_list();
            if (ObjectUtils.listHasData(team_list)) {
                llPintuanvis.setVisibility(View.VISIBLE);
                showRecommend(team_list, detailListLaituantuijiang);
            } else {
                llPintuanvis.setVisibility(View.GONE);
            }
            if (data.getRule() != null && !data.getRule().equals("")) {
                rule.setVisibility(View.VISIBLE);
                detailWebViewrule.loadDataWithBaseURL(null, data.getRule(), "text/html", "utf-8", null);
            } else {
                rule.setVisibility(View.GONE);
            }
            List<String> thumbs = data.getThumbs();
            if (ObjectUtils.listHasData(thumbs)) {
                Banner.addAll(thumbs);
                adapter_banner.notifyDataSetChanged();
            } else {
                banner.setVisibility(View.GONE);
            }
            switch (type) {
                case 1:
                    titleType.setText("拼团");
                    detailTitle.setText("              " + data.getName());
                    break;
                case 2:
                    titleType.setText("新人专享");
                    detailTitle.setText("                      " + data.getName());
                    llPintuanvis.setVisibility(View.GONE);
                    break;
                case 3:
                    titleType.setText("限时秒杀");
                    detailTitle.setText("                      " + data.getName());
                    break;
                case 4:
                    titleType.setText("限时秒杀");
                    detailTitle.setText("                      " + data.getName());
                    break;
                case 5:
                    titleType.setText("免费试用");
                    detailTitle.setText("                      " + data.getName());
                    ruleType.setText("免费试用规则");
                    llPintuanvis.setVisibility(View.GONE);
                    break;
                case 6:
                    titleType.setText("抽奖");
                    detailTitle.setText("              " + data.getName());
                    ruleType.setText("抽奖规则");
                    llPintuanvis.setVisibility(View.GONE);
                    break;
                case 7:
                    titleType.setText("AA团");
                    detailTitle.setText("              " + data.getName());
                    ruleType.setText("AA团规则");
                    llPintuanvis.setVisibility(View.GONE);
                    msp = new SpannableString("￥" + data.getTeam_price_total());
                    msp.setSpan(new AbsoluteSizeSpan(13, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    detailTitleAfter.setText(msp);
                    aaTuanTv.setText(data.getTeam_num() + "人团总价");
                    aaTuanTv2.setVisibility(View.VISIBLE);
                    aaTuanTv2.setText(team_price + "元/人");
                    break;
                case 8:
                    titleType.setText("推广团");
                    detailTitle.setText("                  " + data.getName());
                    ruleType.setText("推广团规则");
                    String share_comss = data.getShare_comss();
                    if (share_comss != null && !share_comss.equals("")) {
                        comssLl.setVisibility(View.VISIBLE);
                        msp = new SpannableString("￥" + share_comss + "+");
                        msp.setSpan(new AbsoluteSizeSpan(12, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        comssPrice.setText(msp);
                    } else {
                        comssLl.setVisibility(View.GONE);
                    }
                    break;
                case 9:
                    titleType.setText("自选团");
                    ruleType.setText("自选团规则");
                    detailTitle.setText("                  " + data.getName());
                    break;
                case 10:
                    titleType.setText("阶梯团");
                    ruleType.setText("阶梯团规则");
                    detailTitle.setText("                  " + data.getName());
                    List<MainDetail.DataBean.StepArrayBean> step_array = data.getStep_array();
                    if (step_array != null && step_array.size() > 0) {
                        pin_ll.setVisibility(View.GONE);
                        adderLl.setVisibility(View.VISIBLE);
                        adderPrice.setText("￥" + data.getDeposit());
                        showAdderAdapt showAdderAdapt = new showAdderAdapt(step_array);
                        adderGridview.setAdapter(showAdderAdapt);

                        if (response.getTeam() != null) {
                            adderTeamLl.setVisibility(View.VISIBLE);
                            adderTeamNumYes.setText(response.getTeam().getTeam_num_yes() + "");
                            adderTeamPrice.setText("￥" + response.getTeam().getTeam_price());
                            adderTeamProgress.setMax(response.getTeam().getTeam_max());
                            adderTeamProgress.setProgress(Integer.parseInt(response.getTeam().getTeam_num_yes()));
                            for (int i = 0; i < step_array.size(); i++) {
                                if (response.getTeam().getTeam_price().equals(step_array.get(i).getStep_value())) {
                                    showAdderAdapt.select(i);
                                }
                            }
                            showAdderAdapt.notifyDataSetChanged();
                        } else {
                            adderTeamLl.setVisibility(View.GONE);
                        }
                    } else {
                        adderLl.setVisibility(View.GONE);
                        pin_ll.setVisibility(View.VISIBLE);
                    }
                    break;
            }
            if (data.getStore() != null) {
                storeMsg.setVisibility(View.VISIBLE);
                storeid = data.getStore().getId();
                ObjectUtils.photo(mcontext, data.getStore().getLogo(), storeLogo);
                storeName.setText(data.getStore().getName());
                storeGoods.setText("商品：" + data.getStore().getGoods_total());
                storeSell.setText("已团：" + data.getStore().getSell_total());
                //店铺推荐
                List<MainDetail.DataBean.TjList> tj_list = data.getTj_list();
                if (ObjectUtils.listHasData(tj_list)) {
                    store_hor_title.setText("店铺推荐");
                    hLl.setVisibility(View.VISIBLE);
                    initTab(tj_list);
                    store_hor_progress.setVisibility(View.GONE);
                } else {
                    hLl.setVisibility(View.GONE);
                }
            } else {
                hLl.setVisibility(View.GONE);
                storeMsg.setVisibility(View.GONE);
            }
            ObjectUtils.GetDataNet(((GoodsDetailActivity) getActivity()).clickResetnetwork, ((GoodsDetailActivity) getActivity()).progress, 1);
        }
    }

    private void initWebContent() {
        if (response.getData().getContent() != null && !response.getData().getContent().equals("")) {
            nodata.setVisibility(View.GONE);
            //宽度适应屏幕
            String js = "<style>\n" +
                    "img{\n" +
                    " max-width:100%;\n" +
                    "height:auto\n" +
                    "}\n" +
                    "</style>" + response.getData().getContent();
            detailWebView.loadDataWithBaseURL(null, js, "text/html", "utf-8", null);
        } else {
            nodata.setVisibility(View.VISIBLE);
        }

    }


    @OnClick({R.id.store_in, R.id.store_msg, R.id.close, R.id.top, R.id.detail_liucheng_detail_ll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.store_in:
            case R.id.store_msg:
                Intent intent = new Intent(mcontext, GoodsStoreActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_STORE_ID, storeid + "");
                startActivity(intent);
                break;
            case R.id.close:
                mcontext.finish();
                break;
            case R.id.detail_liucheng_detail_ll:
                MainMsg mainMsg = new MainMsg(mcontext);
                mainMsg.show(mcontext.getWindow().getDecorView(), 7, null);
                break;
            case R.id.top:
                break;
        }
    }

    private class BannerAdapt extends PagerAdapter {

        @Override
        public int getCount() {
            return Banner.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = inflater.inflate(R.layout.item_fragment_banner, null);
            ImageView photoview = (ImageView) view.findViewById(R.id.imageView1);
            ObjectUtils.photo2(mcontext, Banner.get(position), photoview);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 获取大家都在
     * 团列表数据
     */

    private void GetDataListData(String type) {
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA + "?size=" + 8 + type;
        HttpUtils.get(address, null, new MainListCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(MainList response, int id) {
                listdata.clear();
                if(response == null){
                    return;
                }
                MainList.MainListdata data = response.getData();
                if (data != null && ObjectUtils.listHasData(data.getList())) {
                    listdata.addAll(data.getList());
                    adapter_like.notifyDataSetChanged();
                }
            }
        });
    }

    /**
     * 拼团推荐
     */
    private void showRecommend(final List<MainDetail.DataBean.TeamListBean> list, NestFullListView addview) {
        addview.setAdapter(new NestFullListViewAdapter<MainDetail.DataBean.TeamListBean>(R.layout.item_grid_detail_recommend, list) {
            @Override
            public void onBind(int position, MainDetail.DataBean.TeamListBean testBean, NestFullViewHolder holder) {
                int total = Integer.parseInt(testBean.getTeam_num());
                int total_yes = Integer.parseInt(testBean.getTeam_num_yes());
                int total_no = total - total_yes;
                holder.setText(R.id.item_grid_detail_recommend_phone, testBean.getUsername());
                holder.setText(R.id.item_grid_detail_recommend_tuanshu, "还差" + total_no + "人成团");
                ObjectUtils.photoCircle(mcontext, testBean.getAvatar(), ((ImageView) holder.getView(R.id.item_grid_detail_recommend_img)));
                CountDownTimerView item_grid_detail_recommend_time = holder.getView(R.id.RushBuyCountDownTimerView);
                item_grid_detail_recommend_time.setTime(testBean.getEnd_time());
                item_grid_detail_recommend_time.start();
            }
        });

        addview.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
                Intent intent_tuan = new Intent(mcontext, BaseObject.class);
                intent_tuan.putExtra("title", "团详情");
                intent_tuan.putExtra("need_id", list.get(pos).getId());
                mcontext.startActivity(intent_tuan);
            }
        });

    }

    /**
     * 阶梯团
     */
    private int pos_adder = 0;

    private class showAdderAdapt extends BaseAdapter {
        List<MainDetail.DataBean.StepArrayBean> use_list;

        public showAdderAdapt(List<MainDetail.DataBean.StepArrayBean> use_list) {
            this.use_list = use_list;
        }

        public void refresh(List<MainDetail.DataBean.StepArrayBean> list) {
            use_list = list;
            notifyDataSetChanged();
        }

        // 选中当前选项时，让其他选项不被选中
        public void select(int position) {
            pos_adder = position;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return use_list.size();
        }

        @Override
        public BaseObject getItem(int position) {
            return null;
        }


        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View inflate = inflater.inflate(R.layout.item_gird_detail_zixuan, null);
            TextView tv = (TextView) inflate.findViewById(R.id.tv);
            tv.setText(use_list.get(position).getStep_key() + "人/￥" + use_list.get(position).getStep_value());
            tv.setBackgroundColor(Color.parseColor("#00000000"));
            if (pos_adder == position) {
                tv.setTextColor(Color.parseColor("#FF2741"));
            } else {
                tv.setTextColor(Color.parseColor("#333333"));
            }
            return inflate;
        }
    }

    /**
     * 店铺推荐
     *
     * @param tj_list
     */
    private void initTab(final List<MainDetail.DataBean.TjList> tj_list) {
        //动态设置选项卡宽度，超过2个可以滑动查看
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = (int) (metrics.widthPixels / 2.5);
        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT);
        store_hor_list.setAdapter(new NestFullListViewAdapter<MainDetail.DataBean.TjList>(R.layout.list_main_hor_adapter, tj_list) {
            @Override
            public void onBind(int position, MainDetail.DataBean.TjList testBean, NestFullViewHolder holder) {

                (holder.getView(R.id.item_grid_detail_like_ll)).setLayoutParams(params);
                ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                String price1 = testBean.getTeam_price();
                SpannableString msp = new SpannableString("￥" + price1);
                msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ((TextView) holder.getView(R.id.item_grid_detail_like_number_after)).setText(msp);
                holder.setText(R.id.item_grid_detail_like_number_before, "￥" + testBean.getPrice());
                holder.setText(R.id.item_grid_detail_like_title, testBean.getName());
                ObjectUtils.photo2(mcontext, testBean.getImg_cover(), ((ImageView) holder.getView(R.id.item_grid_detail_like_img)));

            }
        });

        store_hor_list.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
                ObjectUtils.ToDetailActivity(mcontext, 1, tj_list.get(pos).getId(), "");
            }
        });
    }
}
